package com.hundsun.invocation;

import com.hundsun.model.interfaces.ConfigInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.UndeclaredThrowableException;

/**
 * @author jiangwj20966 2018/9/21
 */
public class ConfigUsingInvocationHandler implements InvocationHandler {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private ConfigInfo configInfo;

    public ConfigUsingInvocationHandler(ConfigInfo configInfo) {
        this.configInfo = configInfo;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        String methodName = method.getName();
        if (methodName.startsWith("set") || "addColumnInfo".equals(methodName)) {
            throw new IllegalAccessException("使用者不能修改config字段信息");
        }
        try {
            return method.invoke(configInfo, args);
        } catch (UndeclaredThrowableException e) {
            Throwable t = e.getCause();
            if (t != null) {
                logger.error("未定义异常", t.getMessage());
            } else {
                logger.error("未定义异常", e);
            }
            return null;
        } catch (Exception e) {
            logger.error("未知异常", e);
            return null;
        }
    }
}
